<?php

namespace Controller;
use \Lib\Core\Controller as Controller;

abstract class Base extends Controller {

    public $mustLogin = true;

    public $roles = [];

    public $accountId;

    public $accountInfo;

    private $messages = [];

    protected function actionBefore() {
        $this->getCurrentAccount();
        if ($this->mustLogin) {
            $this->mustLogin();
        }
        $menu = \Entity\AdminMenu::instance()->getMenuList();
        $this->setCurrentUserRoles();
        $this->assign('_menu', $menu);
        $this->assign('_domain', \Entity\Domain::instance());
        $this->assign('_menuPath', array(null, null));
    }

    protected function displayBefore() {
        $this->assign('_messages', $this->messages);
        $this->assign('_accountInfo', $this->accountInfo);
    }

    protected function mustLogin() {
        if (!$this->accountId) {
            $url = '/Passport/Login';
            \Lib\Util\Comm::redirect($url);
        }
        return true;
    }

    protected function setMenuPath($u, $l = null) {
        $this->assign('_menuPath', [$u, $l]);
    }

    protected function setCurrentUserRoles() {
        $this->roles = array('user_add', 'user_show', 'auth');
        $this->assign('_roles', $this->roles);
    }

    protected function addErrorMsg($msg, $code = 0) {
        $this->messages[] = [$msg, $code, 1];
    }

    protected function addWarningMsg($msg, $code = 0) {
        $this->messages[] = [$msg, $code, 2];
    }

    protected function addInfoMsg($msg, $code = 0) {
        $this->messages[] = [$msg, $code, 3];
    }

    protected function addSuccessMsg($msg, $code = 0) {
        $this->messages[] = [$msg, $code, 4];
    }

    protected function encryptionPassword($password) {
        return md5(md5($password));
    }

    private function getCurrentAccount() {
        $id = \Util\Account::getAccountIdToCookie();
        if (!$id) {
            return;
        }
        $info = \Business\Account::instance()->getInfoById($id);
        if (!$info) {
            return;
        }
        $this->accountInfo = $info;
        $this->accountId = $id;
    }

}